const express = require('express');
const router = express.Router();
const { Course, Category, Chapter, User } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound, Conflict } = require('http-errors');

/**
 * 查询分类
 *
 * GET /courses
 * */

router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    if (!query.categoryId) {
      throw new Conflict('获取课程列表失败,分类Id不能为空');
    }

    const condition = {
      attributes: {
        exclude: ['CategoryId', 'UserId', 'content'],
      },
      where: { categoryId: query.categoryId },
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: offset,
    };
    const { count, rows } = await Course.findAndCountAll(condition);
    success(res, '查询成功', {
      courses: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询详情
 *
 * GET /courses
 * */

router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;

    const condition = {
      // distinct: true,
      attributes: {
        exclude: ['CategoryId', 'UserId'],
      },
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name'],
        },
        {
          model: Chapter,
          as: 'chapters',
          attributes: ['id', 'title', 'rank', 'createdAt'],
          // order: [['rank', 'asc'], ['id', 'desc']]
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
          // order: [['rank', 'asc'], ['id', 'desc']]
        },
        // {
        //     model: Chapter,
        //     as: 'chapters',
        //     attributes: ['id', 'title'],
        // }
      ],
      order: [
        [{ model: Chapter, as: 'chapters' }, 'rank', 'ASC'],
        [{ model: Chapter, as: 'chapters' }, 'id', 'DESC'],
      ],
    };
    const course = await Course.findByPk(id, condition);
    if (!course) {
      throw new NotFound(`ID: ${id} 的课程未找到`);
    }
    success(res, '查询成功', {
      course,
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
